package com.example.zhaohang.employmentapp;

import android.graphics.Color;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.example.zhaohang.contect.UriContect;
import com.example.zhaohang.utils.ToastMake;
import com.example.zhaohang.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;

public class CarInformationActivity extends BasicActivity implements View.OnClickListener {


    private TextView mName1;
    private EditText     mName4;
    private LinearLayout mName5;
    private TextView     mName8;
    private EditText     mName9;
    private TextView     mName7;
    private LinearLayout mName11;
    private ImageView    mAgree;
    private TextView     mAgreeText;
    private static final List<String> options1Items = new ArrayList<>();
    private              Handler      mHandler      = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_car_information);
        mName1 = (TextView) findViewById(R.id.name1);
        mName8 = (TextView) findViewById(R.id.name8);
        mName7 = (TextView) findViewById(R.id.name7);
        mAgreeText = (TextView) findViewById(R.id.agree_text);
        mName4 = (EditText) findViewById(R.id.name4);
        mName5 = (LinearLayout) findViewById(R.id.name5);
        mName9 = (EditText) findViewById(R.id.name9);
        mName11 = (LinearLayout) findViewById(R.id.name11);
        mAgree = (ImageView) findViewById(R.id.agree);

        mName1.setOnClickListener(this);
        mAgreeText.setOnClickListener(this);
        mAgree.setOnClickListener(this);
        mName11.setOnClickListener(this);
        mName5.setOnClickListener(this);


        options1Items.clear();
        options1Items.add("托儿索");
        options1Items.add("儿童劫");
        options1Items.add("小学生之手");
        options1Items.add("德玛西亚大保健");
        options1Items.add("面对疾风吧");
        options1Items.add("天王盖地虎");
        options1Items.add("我发一米五");
        options1Items.add("爆刘继芬");

        if (isConnected(CarInformationActivity.this)) {
            showProgrees("加载中请稍等....");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpUtils
                            .get()
                            .url(UriContect.CARS)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ToastMake.showToast(getResources().getString(R.string.name18));
                                    hideProgree();
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    hideProgree();



                                }
                            });
                }
            }).start();
        }


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //提交
            case R.id.name1:

                if (isConnected(CarInformationActivity.this)) {
                    postFrom();
                } else {
                    ToastMake.showToast(getResources().getString(R.string.name17));
                }
                break;
            //选择时间
            case R.id.name11:

                chioceTime();


                break;
            //同意圆圈
            case R.id.agree:

                break;
            //协议书
            case R.id.agree_text:

                break;
            //车辆类型
            case R.id.name5:

                //如果初始化的已经获取车辆名称的列表
                if (options1Items.size() != 0) {
                    chioceCar();
                } else {
                    //如果初始化的没有获取车辆名称的列表
                    getListName();
                }

                break;
        }
    }

    private void chioceCar() {
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(CarInformationActivity.this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String s = options1Items.get(options1);
                mName8.setText(s);
                mName8.setTextColor(getResources().getColor(R.color.textColor5));

            }
        })
                //                        .setSubmitText("确定")//确定按钮文字
                //                        .setCancelText("取消")//取消按钮文字
                .setTitleText("车辆类型")//标题
                .setSubCalSize(20)//确定和取消文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                //                        .setTitleBgColor(0xFF333333)//标题背景颜色 Night mode
                //                        .setBgColor(0xFF000000)//滚轮背景颜色 Night mode
                //                        .setContentTextSize(18)//滚轮文字大小
                //                        .setTextColorCenter(Color.BLUE)//设置选中项的颜色
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                //                        .setLineSpacingMultiplier(1.6f)//设置两横线之间的间隔倍数
                //                        .setLinkage(false)//设置是否联动，默认true
                //                        .setLabels("省", "市", "区")//设置选择的三级单位
                //                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //                        .setCyclic(false, false, false)//循环与否
                //                        .setSelectOptions(1, 1, 1)  //设置默认选中项
                //                        .setOutSideCancelable(false)//点击外部dismiss default true
                //                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvOptions.setPicker(options1Items);
        pvOptions.show();
    }

    private void chioceTime() {
        TimePickerView pvTime = new TimePickerView.Builder(CarInformationActivity.this, new TimePickerView.OnTimeSelectListener() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调

                long chioceDate = Utils.dateToLong(date2);
                long curDate = Utils.getCurDate();
                if (chioceDate >= curDate) {
                    ToastMake.showToast("时间必须小于当前时间");
                    return;
                } else {
                    String validDateStr = getValidDateStr(date2);
                    mName7.setText(validDateStr);
                    mName7.setTextColor(getResources().getColor(R.color.textColor5));
                }
            }
        })
                .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(Color.BLUE)//确定按钮文字颜色
                .setCancelColor(Color.BLUE)//取消按钮文字颜色
                //                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
                //                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
                //                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
                //                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                //                        .setRangDate(startDate,endDate)//起始终止年月日设定
                //                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                //                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }

    //提交车辆信息
    private void postFrom() {
        String carNumber = mName4.getText().toString().trim();
        String carType = mName8.getText().toString().trim();
        String carMasterName = mName9.getText().toString().trim();
        String carDate = mName7.getText().toString().trim();
        if (carNumber.length() != 7) {
            ToastMake.showToast(getResources().getString(R.string.string13));
            return;
        }
        if (!Utils.isCar(carNumber)) {
            ToastMake.showToast(getResources().getString(R.string.string14));
            return;
        }
        if (TextUtils.equals(carType, getResources().getString(R.string.string7))) {
            ToastMake.showToast(getResources().getString(R.string.string15));
            return;
        }
        if (TextUtils.isEmpty(carMasterName)) {
            ToastMake.showToast(getResources().getString(R.string.string9));
            return;
        }

        if (carDate.contains("xx")) {
            ToastMake.showToast(getResources().getString(R.string.string16));
            return;
        }

        final Map<String, String> map = new HashMap<>();
        map.put("phone", MyApplayCation.phone);
        map.put("name", MyApplayCation.driverInfo.getName());
        map.put("card", MyApplayCation.driverInfo.getCard());
        map.put("plate", carNumber);
        map.put("receive", MyApplayCation.driverInfo.getReceive());
        map.put("model", carType);
        map.put("joindate", carDate);

        showProgrees("提交中,请稍等.....");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String separator = File.separator;
                OkHttpUtils.post()//
                        .addFile("pic", separator+"01.png", MyApplayCation.driverInfo.getIcon())//
                        .addFile("idcard", separator+"02.png", MyApplayCation.driverInfo.getId())//
                        .url(UriContect.PERFECT)
                        .params(map)
                        .build()//
                        .execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastMake.showToast(getResources().getString(R.string.name18));
                                hideProgree();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                hideProgree();

                                //上传完成以后,跳转到绑定界面
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        skipOtherActivity(BundingSetActivity.class,false);
                                    }
                                });

                            }
                        });
            }
        }).start();

    }

    /**
     * 时间转换
     *
     * @param data
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public String getValidDateStr(Date data) {
        String sDate = "";
        SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
        try {
            Date date = sdf1.parse(sdf1.format(data));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            sDate = sdf.format(date);
        } catch (Exception e) {

        }
        return sDate;
    }

    public void getListName() {
        if (isConnected(CarInformationActivity.this)) {
            showProgrees("加载中请稍等....");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    OkHttpUtils
                            .get()
                            .url(UriContect.CARS)
                            .build()
                            .execute(new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                    ToastMake.showToast(getResources().getString(R.string.name18));
                                    hideProgree();

                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    hideProgree();


                                    //切换到主线程去做
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            chioceCar();
                                        }
                                    });
                                }
                            });
                }
            }).start();
        }

    }
}
